#include "ota_http.h"

size_t getText(char *ptr, size_t size, size_t nmemb, void *userdata)
{
    // 收到的实际字节数
    size_t realsize = size * nmemb;
    memcpy(userdata, ptr, realsize);
    ((char *)userdata)[realsize] = '\0';
    return realsize;
}

/**
 * @brief 从指定的url获取文本数据
 *
 * @param url
 * @return char* 获取到的字符串
 */
char *ota_http_getText(char *url)
{
    CURL *curl;
    CURLcode res;

    // 初始化全局环境(只需要初始化一次)
    curl_global_init(CURL_GLOBAL_DEFAULT);

    // 得到curl句柄
    curl = curl_easy_init();
    if (curl == NULL)
    {
        log_error("curl_easy_init() failed");
        return NULL;
    }

    // 设置url地址
    curl_easy_setopt(curl, CURLOPT_URL, url);

    // 设置回调函数,接收收到的数据
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, getText);

    char *buffer = malloc(1024);
    memset(buffer, 0, 1024);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, buffer);

    // 执行请求
    res = curl_easy_perform(curl);

    if (res != CURLE_OK)
    {

        fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));
        curl_easy_cleanup(curl);
        return NULL;
    }

    curl_easy_cleanup(curl);

    return buffer;
}

/**
 * @brief 下载文件
 *
 * @param url
 * @param file_path
 */
gate_status_t ota_http_download(char *url, char *file_path)
{
    CURL *curl;
    CURLcode res;

    curl = curl_easy_init();

    if (curl == NULL)
    {
        log_error("curl_easy_init() failed");
        return GATE_ERROR;
    }

    // 设置url地址
    curl_easy_setopt(curl, CURLOPT_URL, url);
    // fwrite
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite);

    FILE *fp = fopen(file_path, "wb");
    if (fp == NULL)
    {
        log_error("fopen() failed");
        return GATE_ERROR;
    }
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

    // 执行请求
    res = curl_easy_perform(curl);

    if (res != CURLE_OK)
    {

        fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));
        curl_easy_cleanup(curl);
        return GATE_ERROR;
    }

    curl_easy_cleanup(curl);

    fclose(fp);
    return GATE_OK;
}
